<script setup>
    import {
        onBeforeMount,
        reactive,
        ref
    } from "vue";
    import {
        ElNotification,
        ElMessageBox,
        ElMessage
    } from "element-plus";
    import api from "../api";
    import path from "../utils/api"
    import request from "../utils/request";

    import axios from "axios";
    
    const img_url = path.IMG_URL;

    let seleValue = ref([]);
    let seaValue = ref(""); //搜索框的内容
    let seaOld = ref("");
    let isClick = ref(true); //防抖
    const options = [
        {value: "2",label: "待服务"},
        {value: "3",label: "已完成"},
        {value: "4",label: "退款中"},
        {value: "5",label: "已退款"},
    ];
    let total = ref(0); //分页总条数
    let currentPage = ref(1); //当前分页
    let pageSize = ref(14); //每页显示的数量
    //let pageTotal = ref(5); //总页数
    let loading = ref(false);

    let tableData = ref([]);
    let showDetail = ref(false);
    const detailArr = ref({}); //单个订单的详情

    //渲染之前获取数据
    onBeforeMount(() => {
        getOrderDataList(seleValue.value, currentPage.value, pageSize.value,"");
    });
    //获取数据
    const getOrderDataList = (seleList, currentPage, pageSize,seaZhi) => {
        let sele_arr = [];
        sele_arr = seleList.length == 0 ? [2, 3, 4, 5] : seleList;
        if (isClick.value) {
            isClick.value = false;
            loading.value = true;
            request.ajax({
                    needToken: true,
                    url: "/car_wash_api/v1/admin/home/order_list",
                    data: {
                        type_list: sele_arr,
                        page_num: currentPage,
                        page_size: pageSize,
						keyword : seaZhi
                    },
                },
                (result) => {
                    const {code,data,message} = result;
                    setTimeout(() => {
                        isClick.value = true;
                        loading.value = false;
                    }, 500);
                    if(code === 10000){
                        tableData.value = data.data;
                        detailArr.value = tableData.value[0];
                        total.value = data.total;
                        tableData.value.forEach((item,index)=>{
                            item.start_service_time = item.start_service_time || "/";
                            item.address = item.address || "/";
                        })
                    }else{
                        ElMessage({
                            message: '获取数据接口异常',
                            type: "warning",
                            duration: 2000,
                        });
                    }
                },
                (fail) => {
                    isClick.value = true;
                    loading.value = false;
                }
            );
        }
    };

    //选择订单状态
    const seleChange = (e) => {
        seleValue.value = e;
        currentPage.value = 1;
        getOrderDataList(e, currentPage.value, pageSize.value,"");
    };
    //搜索提交
    const handleEnter = () => {
        if (isClick.value) {
            if (seaValue.value === "") {
                ElMessage({
                    message: "提示, 请输入搜索内容",
                    type: "warning",
                    duration: 1000,
                });
                return false;
            } else {
                if (seaOld.value === seaValue.value) {
                    //防止同一个字段 重复搜索
                    return false;
                } else {
					currentPage.value = 1;
                    getOrderDataList([2,3,4,5], currentPage.value, pageSize.value,seaValue.value);
                }
                seaOld.value = seaValue.value;
            }
        }
    };
	const reset = ()=>{
		currentPage.value = 1;
		seaValue.value = "";
		seleValue.value = [];
		getOrderDataList(seleValue.value, currentPage.value, pageSize.value,seaValue.value);
	}
    //核销
    const hexiao = (row) => {
        //订单id
        //console.log(row.id);
        ElMessageBox.confirm("操作订单核销后，表示该订单已服务完成，订单状态由<待服务>变为<已完成>。", "确认将该订单核销？", {
                confirmButtonText: "确认",
                cancelButtonText: "取消",
                draggable: true,
            })
            .then(() => {
				loading.value = true;
				request.ajax({
				        needToken: true,
				        url: "/car_wash_api/v1/admin/home/verification_order",
				        data: {
				            order_id: row.id,
				        },
				    },
				    (result) => {
				        const {code,data,message} = result;
				        setTimeout(() => {
				            loading.value = false;
				        }, 500);
				        if(code === 10000){
				            getOrderDataList(seleValue.value, currentPage.value, pageSize.value,"");
							ElMessage({
							    message: '核销成功',
							    type: "success",
							    duration: 2000,
							});
				        }else{
				            ElMessage({
				                message: '获取数据接口异常',
				                type: "warning",
				                duration: 2000,
				            });
				        }
				    },
                    (fail) => {
                        loading.value = false;
                    }
				);
            })
            .catch(() => {});
    };
    //退款
    const tuikuan = (row,action) => {
        //订单id
		let text1 = action == 0 ? "拒绝退款后，订单状态由<退款中>变为<待服务>。" : "同意退款后，订单状态由<退款中>变为<已退款>。"
		let text2 = action == 0 ? "拒绝" : "同意";
        //console.log(row.id);
        ElMessageBox.confirm(text1, `确认${text2}退款？`, {
                confirmButtonText: "确认",
                cancelButtonText: "取消",
                draggable: true,
            })
            .then(() => {
				request.ajax({
				        needToken: true,
				        url: "/car_wash_api/v1/admin/home/process_approve",
				        data: {
				            order_id: row.id,
							action : action
				        },
				    },
				    (result) => {
				        const {code,data,message} = result;
				        setTimeout(() => {
				            loading.value = false;
				        }, 500);
				        if(code === 10000){
				            getOrderDataList(seleValue.value, currentPage.value, pageSize.value,"");
							ElMessage({
							    message: `已${text2}退款`,
							    type: "success",
							    duration: 2000,
							});
				        }else{
				            ElMessage({
				                message: '获取数据接口异常',
				                type: "warning",
				                duration: 2000,
				            });
				        }
				    },
                    (fail) => {
                        loading.value = false;
                    }
				);
            })
            .catch(() => {});
    };
    //监听分页改变
    const pageChange = (e) => {
        currentPage.value = e;
        getOrderDataList(seleValue.value, currentPage.value, pageSize.value,seaValue.value);
    };
    //处理时间
    const getTimes = (time) => {
        return time.split(".")[0].replace("T", " ");
    };
    //控制单元格样式
    const cellClassName = (data)=>{
        if (data.columnIndex === 0 || data.columnIndex === 8) {
            return "bold"
        }
    }
    const activeHeader = (data) =>{
        return "titBold"
    }
    //查看详情
    const detail = (row) => {
        detailArr.value = tableData.value.filter(item => item.id == row.id)[0] || {};
        showDetail.value = true;
    };
</script>

<template>
    <div class="order">
        <!-- 筛选和搜索 -->
        <div class="or_top">
            <!-- 筛选 -->
            <div class="shai">
                <el-select v-model="seleValue" multiple clearable @change="seleChange" placeholder="默认展示全部"
                    style="width: 345px">
                    <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
            </div>
            <div class="search">
                <el-input v-model.trim="seaValue" class="inputs" placeholder="姓名/用户手机号/订单号" prefix-icon="Search"
                    @keyup.enter="handleEnter" />
                <el-button class="seaBtns" type="primary" @click="handleEnter">搜索</el-button>
            </div>
			<el-button class="reset" type="success" @click="reset">重置</el-button>
        </div>

        <!-- 列表 -->
        <div class="results">
            <div class="list" v-if="tableData.length" v-loading="loading">
                <el-table :data="tableData" style="width: 100%" stripe row-key="id"
                    :scrollbar-always-on="true"
                    :header-cell-style="{ textAlign: 'center',fontWeight:'bold' }"
                    :cell-style="{ textAlign: 'center'}"
                    :cell-class-name="cellClassName"
                    :header-cell-class-name='activeHeader'
                >
                    <el-table-column prop="id" label="订单id" width="70" />
					<el-table-column prop="order_no" label="订单号" width="160" />
                    <el-table-column label="下单时间" width="170" >
                        <template v-slot="scope">
                            {{ getTimes(scope.row.create_time) }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="full_name" label="姓名" width="70" />
                    <el-table-column prop="mobile_phone" label="电话" width="130" />
                    <el-table-column prop="plate_number" label="车牌" width="120" />
                    <el-table-column prop="start_service_time" label="上门服务时间" width="160" />
                    <el-table-column prop="order_total_price" label="订单价格" width="90" />
                    <el-table-column label="订单类型" width="120" >
                        <template v-slot="scope">
                            <p v-if="scope.row.user_level==1">非会员</p>
                            <p v-else>会员</p>
                        </template>
                    </el-table-column>
                    <el-table-column label="支付方式" width="120" >
                        <template v-slot="scope">
                            <p v-if="scope.row.pay_type==1">微信支付</p>
                            <p v-else>余额支付</p>
                        </template>
                    </el-table-column>
					<el-table-column fixed="right" label="订单状态" width="100" >
					    <template v-slot="scope">
					        <p v-if="scope.row.status_code==2" class="c2">待服务</p>
					        <p v-if="scope.row.status_code==3" class="c3">已完成</p>
					        <p v-if="scope.row.status_code==4" class="c4">退款中</p>
					        <p v-if="scope.row.status_code==5" class="c5">已退款</p>
					    </template>
					</el-table-column>
                    <el-table-column fixed="right" label="操作" width="195">
                        <template v-slot="scope">
                            <el-button v-if="scope.row.status_code=='2'" type="success" size="small" @click="hexiao(scope.row)">核销</el-button>
							<el-button v-if="scope.row.status_code=='4'" type="warning" size="small" @click="tuikuan(scope.row,0)">拒绝</el-button>
                            <el-button v-if="scope.row.status_code=='4'" type="primary" size="small" @click="tuikuan(scope.row,1)">同意</el-button>
                            <el-button type="primary" plain size="small" @click="detail(scope.row)">查看</el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <div class="fenye">
                    <el-pagination background layout="total,prev, pager, next" v-model:current-page="currentPage"
                        :page-size="pageSize" :total="total" @change="pageChange" />
                </div>
            </div>

            <el-empty class="error" description="暂无数据" v-else>
                <!-- <el-button type="primary" @click="go_order">回到全部订单</el-button> -->
            </el-empty>
        </div>
        <!-- 单个订单详情 -->
        <el-dialog v-model="showDetail" width="600">
            <div class="de_box">
                <p class="deTit">该订单为 {{ detailArr.user_level == 1 ? "非会员价" : "会员价" }}</p>
                <p class="orderNum">地址：{{ detailArr.address || "未填写地址" }}</p>
                <div class="deItem" v-for="(item,index) in detailArr.snapshot_list" :key="item.id">
                    <img class="deImg" :src="img_url+item.main_image_1" alt="" />
                    <div class="deCen">
                        <p class='deBiao'>{{ item.title }}</p>
                        <p class='deType'>{{ item.category_level1 }}、{{ item.category_level2 }}</p>
                        <p class='deJia'>
                            <span>￥{{ detailArr.user_level == 1 ? item.origin_price : item.price }}</span>
                            <span>x{{ item.total }}</span>
                        </p>
                    </div>
                </div>
            </div>
        </el-dialog>
        
    </div>
</template>

<style lang="scss">
    /*  公共颜色 */
    $main: #409eff;

    .order {
        font-size: 15px;
        width: 100%;
        min-width: 860px;
        margin: 0 auto;

        .or_top {
            display: flex;
            align-items: center;

            /* 筛选 */
            .shai {
                display: flex;
                align-items: center;
                background-color: #fff;
                overflow: hidden;
            }

            /* 搜索 */
            .search {
                display: flex;margin-left: 15px;
                align-items: center;

                .inputs {
                    width: 240px;
                    margin-right: 5px;
                    font-size: 14px;

                    &:focus {
                        border: 1px solid $main;
                    }
                }

                .seaBtns {
                    background-color: $main;
                    border: none;
                }
            }
			.reset{
				margin-left: 5px;
			}
        }

        //列表
        .results {
            height: calc(100vh - 105px);
            position: relative;

            .list {
                padding: 10px 0 0 0;

                .fenye {
                    text-align: center;
                    width: 100%;

                    .el-pagination {
                        margin: 20px auto;
                        display: inline-flex;
                    }
                }
            }

            .error {
                position: absolute;
                left: 50%;
                top: 40%;
                transform: translate(-50%, -50%);
            }
        }
        
        /* 单个订单详情 */
        .de_box{
            color: #909399;font-size: 14px;
            .deTit{text-align: center;font-size: 14px;color: #000;}
            .orderNum{margin: 12px 0 8px;}
            .deItem{
                display: flex;border-top: 1px solid #C4C4C4;
                padding: 15px 13px;
                &:last-child{border-bottom: 1px solid #C4C4C4;}
                .deImg{width:80px;height: 80px;border-radius: 5px;}
                .deCen{
                    margin-left:18px ;
                    .deBiao{
                        color:#343434;overflow:hidden;white-space: nowrap;
                        text-overflow:ellipsis;width:100%;
                    }
                    .deType{margin-top: 5px;font-size: 13px;}
                    .deJia{
                        margin-top:5px;display: flex;justify-content: space-between;
                        width: 100px;
                    }
                }
            }
        }
        
    }

    .el-pagination.is-background .btn-next,
    .el-pagination.is-background .btn-prev,
    .el-pagination.is-background .el-pager li {
        border: 1px solid $main;
        background-color: #fff;
    }
    .c2 { color: #409EFF; }
    .c3 { color: #67C23A; }
    .c4 { color: #F56C6C; }
    .c5 { color: #E6A23C; }
    .bold { .cell {font-weight: bold;} }
    .titBold { .cell {font-weight: bold;color:#343434;} }
    .el-dialog{background-color:#FFF;}
    .box header{
        padding: 0 0 0 0;height: 0px;opacity: 1;
    }
</style>